package com.aliang.demospringmvc.servlet;

import com.aliang.demospringmvc.annotation.*;
import sun.misc.Request;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "dispatcherServlet",urlPatterns = "/" ,loadOnStartup = 1
        ,initParams = {@WebInitParam(name="base-package",value = "com.aliang.demospringmvc")})
public class DispatcherServlet extends HttpServlet {


    /*** 扫描的基包 ***/
    private String basePackage = "" ;
    /*** 基包下面所有的带包路径全限定类名 ***/
    private List<String> packageNames = new ArrayList<>();
    /*** 注解实例化 注解上的名称:实例化对象 ***/
    private Map<String,Object> instanceMap = new HashMap<>();
    /*** 带包路径的全限定名称：注解上的名称 classPaht : instanceName ***/
    private Map<String,String> nameMap  = new HashMap<>();
    /*** URL地址和方法的映射关系 springMvc 调用链   url:method ***/
    private Map<String,Method> urlMethodMap = new HashMap<>();
    /*** Method 和全限定类名映射关系 method : className  主要是为了通过Method找到方法的对象利用反射来执行 ***/
    private Map<Method,String> methodPackageMap = new HashMap<>();

    @Override
    public void init(ServletConfig config) throws ServletException {

        basePackage = config.getInitParameter("base-package");

        try {

            /*** 1.扫描基包得到全部带包路径的全限定名  ***/
            scanBasePackage(basePackage);

            /*** 2.把带有@Controller/@Service/@Repository 注解的类实例化放入instanceMap 中，key 为注解的value ***/
            instance(packageNames);

            /*** 3.springIOC  ***/
            springIOC();

            /*** 4.URL映射处理 ***/
            handlerUrlMethodMap();


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        String contextPath = req.getContextPath();
        String path = uri.replace(contextPath,"");

        Method method = urlMethodMap.get(path);
        if(method != null ){
            String className = methodPackageMap.get(method);
            String instanceName = nameMap.get(className);

            Object contorllerObject = instanceMap.get(instanceName);

            try {

                method.setAccessible(true);
                method.invoke(contorllerObject);

            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    /***
     * 扫描基包得到全部带包路径的全限定名
     * @param basePackage
     */
    private void scanBasePackage(String basePackage) {
        String packagePath = basePackage.replaceAll("\\.","/");
        URL url = this.getClass().getClassLoader().getResource(packagePath);
        File basePackageFile = new File(url.getPath());
        File[] files = basePackageFile.listFiles();
        for(File file:files){
            if(file.isDirectory()){
                scanBasePackage(basePackage+"."+file.getName());
            }else if(file.isFile()){
                String[] fileName = file.getName().split("\\.");
                packageNames.add(basePackage+"."+fileName[0]);
                System.out.println("描述到文件："+basePackage+"."+fileName[0]);
            }
        }
    }

    /***
     * 实例化 packageNames 中的所有带@Controller/@Service/@Repository 注解的类
     * @param packageNames
     */
    private void instance(List<String> packageNames) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        if(packageNames.size() < 0){
            return ;
        }
        for(String className:packageNames){
            Class clazz = Class.forName(className);
            if(clazz.isAnnotationPresent(Controller.class)){
                Controller controller = (Controller) clazz.getAnnotation(Controller.class);
                String instanceName = controller.value();
                instanceMap.put(instanceName,clazz.newInstance());
                nameMap.put(className,instanceName);
                System.out.println("实例化------>"+instanceName+" ==== "+className);

            }else if(clazz.isAnnotationPresent(Service.class)){
                Service service = (Service) clazz.getAnnotation(Service.class);
                String instanceName = service.value();
                instanceMap.put(instanceName,clazz.newInstance());
                nameMap.put(className,instanceName);
                System.out.println("实例化------>"+instanceName+" ==== "+className);

            }else if(clazz.isAnnotationPresent(Repository.class)){
                Repository repository = (Repository) clazz.getAnnotation(Repository.class);
                String instanceName = repository.value();
                instanceMap.put(instanceName,clazz.newInstance());
                nameMap.put(className,instanceName);
                System.out.println("实例化------>"+instanceName+" ==== "+className);

            }
        }
    }

    /***
     *
     * 将instanceMap 中实例化对象的属性依赖注入
     *
     */
    private void springIOC() throws IllegalAccessException {
        if(instanceMap.size()<1){
            return ;
        }
        for(Map.Entry<String,Object> entry:instanceMap.entrySet()){
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for(Field field:fields){
                if(field.isAnnotationPresent(Qualifier.class)){
                    String name = field.getDeclaredAnnotation(Qualifier.class).value();
                    field.setAccessible(true);
                    field.set(entry.getValue(),instanceMap.get(name));
                    System.out.println("注入------->"+ name );
                }
            }
        }

    }


    /***
     *
     * 处理URL映射
     *
     */
    private void handlerUrlMethodMap() throws ClassNotFoundException {
        if(packageNames.size()<1){
            return ;
        }
        for(String className:packageNames){

            Class clazz = Class.forName(className);
            if(clazz.isAnnotationPresent(Controller.class)){

                Method[] methods = clazz.getMethods();
                String basePath = "";
                if(clazz.isAnnotationPresent(RequestMapping.class)){
                    RequestMapping classRequestMapping = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
                    basePath = classRequestMapping.value();
                }
                for(Method method:methods){
                    if(method.isAnnotationPresent(RequestMapping.class)){
                        RequestMapping methodRequestMapping = (RequestMapping) method.getAnnotation(RequestMapping.class);
                        String path = (basePath==null?"":basePath)+methodRequestMapping.value();
                        urlMethodMap.put(path,method);
                        methodPackageMap.put(method,className);
                        System.out.println("生成的映射路径---------->"+path);

                    }
                }
            }
        }
    }


    public static void main(String[] args) {
        String basePackage = "com.aliang.demospringmvc";
        System.out.println(basePackage.replaceAll("\\.","/"));
    }

}
